import React, { useState, useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { creditsService, CreditPackage, UserCredits, CREDIT_PACKAGES } from '../services/credits';
import StripePayment from '../components/StripePayment';
import CreditPackageGrid from '../components/CreditPackageGrid';

const BuyCredits: React.FC = () => {
  const [userCredits, setUserCredits] = useState<UserCredits | null>(null);
  const [creditPackages, setCreditPackages] = useState<CreditPackage[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingCredits, setIsLoadingCredits] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  
  // 支付相关状态
  const [showPaymentModal, setShowPaymentModal] = useState(false);
  const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null);

  const { user, isAuthenticated } = useAuth();
  const history = useHistory();

  // 加载用户积分信息 - 使用useCallback避免依赖问题
  const loadUserCredits = useCallback(async () => {
    if (!user) return;
    
    setIsLoadingCredits(true);
    try {
      const credits = await creditsService.getUserCredits(user.id);
      setUserCredits(credits);
    } catch (error: any) {
      console.error('Failed to load user credits:', error);
      setError('Failed to load credit information');
    } finally {
      setIsLoadingCredits(false);
    }
  }, [user]);

  // 加载积分包和用户积分信息
  useEffect(() => {
    loadCreditPackages();
    if (isAuthenticated && user) {
      loadUserCredits();
    } else {
      setIsLoadingCredits(false);
    }
  }, [isAuthenticated, user, loadUserCredits]);

  // 加载积分包列表
  const loadCreditPackages = async () => {
    try {
      const packages = await creditsService.getCreditPackages();
      setCreditPackages(packages);
    } catch (error: any) {
      console.error('Failed to load credit packages:', error);
      // 使用fallback数据
      setCreditPackages(CREDIT_PACKAGES);
    }
  };

  // 处理购买按钮点击
  const handlePurchase = async (creditPackage: CreditPackage) => {
    // 检查用户是否登录
    if (!isAuthenticated || !user) {
      setError('Please login first to purchase credits');
      setTimeout(() => {
        history.push('/login');
      }, 3000);
      return;
    }

    // 显示支付弹窗
    setSelectedPackage(creditPackage);
    setShowPaymentModal(true);
    setError('');
    setSuccess('');
  };

  // 处理支付成功
  const handlePaymentSuccess = async (paymentIntent: any) => {
    if (!selectedPackage || !user) return;

    setIsLoading(true);
    setShowPaymentModal(false);

    try {
      // 调用后端API处理支付成功
      const updatedCredits = await creditsService.handlePaymentSuccess(
        user.id,
        selectedPackage.id,
        paymentIntent.id
      );
      
      setUserCredits(updatedCredits);
      setSuccess(`Successfully purchased ${selectedPackage.credits} credits! Your new balance is ${updatedCredits.creditBalance} credits.`);
      
      // 清除成功消息
      setTimeout(() => {
        setSuccess('');
      }, 10000);
    } catch (error: any) {
      setError(error.message || 'Failed to process payment. Please contact support if credits were charged.');
    } finally {
      setIsLoading(false);
      setSelectedPackage(null);
    }
  };

  // 处理支付错误
  const handlePaymentError = (errorMessage: string) => {
    setError(errorMessage);
    setShowPaymentModal(false);
    setSelectedPackage(null);
    
    setTimeout(() => {
      setError('');
    }, 5000);
  };

  // 处理支付取消
  const handlePaymentCancel = () => {
    setShowPaymentModal(false);
    setSelectedPackage(null);
  };

  // 格式化过期信息显示
  const formatExpirationInfo = () => {
    if (!userCredits) return null;
    
    const expirationInfo = creditsService.formatExpirationInfo(userCredits);
    
    if (!expirationInfo.message) return null;
    
    const colorClass = {
      'error': 'text-red-600',
      'warning': 'text-orange-600',
      'info': 'text-gray-600'
    }[expirationInfo.type || 'info'];

    return (
      <div className={`text-sm ${colorClass}`}>
        {expirationInfo.message}
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 py-12">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">Buy Credits</h1>
          <p className="text-xl text-gray-600">Purchase credits to use our AI room design features</p>
          
          {/* 当前积分状态 */}
          <div className="mt-6 bg-white rounded-xl shadow-sm p-6 max-w-md mx-auto">
            <div className="text-center">
              {isLoadingCredits ? (
                <div className="animate-pulse">
                  <div className="h-8 bg-gray-200 rounded mb-2"></div>
                  <div className="h-4 bg-gray-200 rounded mb-2"></div>
                  <div className="h-4 bg-gray-200 rounded w-2/3 mx-auto"></div>
                </div>
              ) : (
                <>
                  <div className="text-3xl font-bold text-blue-600 mb-2">
                    {userCredits?.creditBalance || 0}
                  </div>
                  <div className="text-gray-600 mb-2">Current Credit Balance</div>
                  {formatExpirationInfo()}
                </>
              )}
            </div>
          </div>

          {/* 登录提示 */}
          {!isAuthenticated && (
            <div className="mt-6 bg-yellow-50 border border-yellow-200 rounded-lg p-4 max-w-md mx-auto">
              <div className="text-yellow-800">
                <p className="font-medium">Please Login First</p>
                <p className="text-sm">You need to login to purchase credits</p>
                <button
                  onClick={() => history.push('/login')}
                  className="mt-2 text-blue-600 hover:text-blue-800 font-medium"
                >
                  Login Now →
                </button>
              </div>
            </div>
          )}
        </div>

        {/* 全局消息显示 */}
        {error && (
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="mb-6 bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-lg max-w-2xl mx-auto"
            role="alert"
          >
            <span className="block sm:inline">{error}</span>
          </motion.div>
        )}

        {success && (
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="mb-6 bg-green-50 border border-green-200 text-green-600 px-4 py-3 rounded-lg max-w-2xl mx-auto"
            role="alert"
          >
            <span className="block sm:inline">{success}</span>
          </motion.div>
        )}

        {/* 积分包选择 */}
        <CreditPackageGrid
          creditPackages={creditPackages}
          isLoading={isLoading}
          isAuthenticated={isAuthenticated}
          onPurchase={handlePurchase}
          defaultHighlightIndex={1}
        />

        {/* FAQ部分 */}
        <div className="mt-16 bg-white rounded-xl shadow-lg p-8">
          <h2 className="text-2xl font-bold text-gray-900 mb-6">Frequently Asked Questions</h2>
          <div className="space-y-6">
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">How do credits work?</h3>
              <p className="text-gray-700">
                Each credit allows you to generate one AI room redesign. Simply upload a photo of your room,
                select a style, and use one credit to see the transformation.
              </p>
            </div>
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">How long are credits valid for?</h3>
              <p className="text-gray-700">
                Credits are valid for the period specified in your plan (30, 60, or 90 days from purchase).
                We'll remind you before they expire.
              </p>
            </div>
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">Can I get a refund?</h3>
              <p className="text-gray-700">
                We currently do not offer refunds for purchased credits. If you have any issues,
                please contact our support team.
              </p>
            </div>
            <div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">Is payment secure?</h3>
              <p className="text-gray-700">
                We use industry-leading Stripe payment processing to ensure your payment information is secure.
                We never store your credit card information.
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* 支付弹窗 */}
      {showPaymentModal && selectedPackage && user && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-white rounded-xl shadow-xl max-w-md w-full max-h-[90vh] overflow-y-auto"
          >
            <div className="p-6">
              <div className="flex justify-between items-center mb-6">
                <h3 className="text-xl font-bold text-gray-900">
                  Purchase {selectedPackage.name}
                </h3>
                <button
                  onClick={handlePaymentCancel}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              <StripePayment
                creditPackage={selectedPackage}
                userId={user.id.toString()}
                onSuccess={handlePaymentSuccess}
                onError={handlePaymentError}
                onCancel={handlePaymentCancel}
              />
            </div>
          </motion.div>
        </div>
      )}

      {/* 加载遮罩 */}
      {isLoading && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 flex items-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mr-3"></div>
            <span className="text-gray-700">Processing your purchase...</span>
          </div>
        </div>
      )}
    </div>
  );
};

export default BuyCredits;